package org.graduation.rbac.controller;

import org.graduation.model.common.RBAC.Roles;
import org.graduation.model.common.ResponseResult;
import org.graduation.model.common.note.Note;
import org.graduation.model.common.user.User;
import org.graduation.model.dtos.RBAC.UserAndNotePermissionsCheckerDTO;
import org.graduation.rbac.service.UserAndNotePermissionsService;
import org.graduation.utils.ResponseResultUtil;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/rbac/note")
public class NotePermissionsController {

    @Autowired
    private Token token;
    @Autowired
    private UserAndNotePermissionsService userAndNotePermissionsService;

    @RequestMapping(value = "/assign_role", method = RequestMethod.POST)
    public ResponseResult assignRole(@RequestBody Note note, HttpServletRequest httpServletRequest) {
        //只用到note的id
        int uid = token.getUidByToken(token.getTokenByRequest(httpServletRequest));
        User user = new User();
        user.setUid(uid);
        return userAndNotePermissionsService.assignRole(user, note, Roles.NOTE_CREATOR);
    }

    @RequestMapping(value = "/revoke_role", method = RequestMethod.POST)
    public ResponseResult revokeRole(@RequestBody Note note, HttpServletRequest httpServletRequest) {
        //只用到note的id
        int uid = token.getUidByToken(token.getTokenByRequest(httpServletRequest));
        User user = new User();
        user.setUid(uid);
        return userAndNotePermissionsService.revokeRole(user, note, Roles.NOTE_CREATOR);
    }

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public ResponseResult check(@RequestBody UserAndNotePermissionsCheckerDTO dto) {
        return ResponseResultUtil.simpleCheck(userAndNotePermissionsService.checkPermission(dto.getUser(), dto.getModel(), dto.getPermissions()));
    }
}
